<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Java扩展类5：AWT绘图和音频播放、打印技术, blog">
    <meta name="description" content="这是我的个人网站，欢迎来访">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Java扩展类5：AWT绘图和音频播放、打印技术 | 头号咸鱼</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

    <script>(function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/7b318e23.js","daovoice")</script>
    

<meta name="generator" content="Hexo 5.3.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="头号咸鱼" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">头号咸鱼</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">头号咸鱼</div>
        <div class="logo-desc">
            
            这是我的个人网站，欢迎来访
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-g8logq.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Java扩展类5：AWT绘图和音频播放、打印技术</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                                <span class="chip bg-color">编程语言</span>
                            </a>
                        
                            <a href="/tags/Java%E6%89%A9%E5%B1%95%E7%B1%BB/">
                                <span class="chip bg-color">Java扩展类</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Java/" class="post-category">
                                Java
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-02-19
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2021-02-19
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    7k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    34 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="一、AWT绘图和音频播放"><a href="#一、AWT绘图和音频播放" class="headerlink" title="一、AWT绘图和音频播放"></a>一、AWT绘图和音频播放</h2><h4 id="1-Java绘图"><a href="#1-Java绘图" class="headerlink" title="1.Java绘图"></a>1.Java绘图</h4><h6 id="Graphics"><a href="#Graphics" class="headerlink" title="Graphics"></a>Graphics</h6><p>Graphics类是所有图形上下文的抽象基类，它允许应用程序在组件以及闭屏图像上进行绘制。Graphics类封装了Java支持的基本绘图操作所需的状态信息，主要包括颜色、字体、画笔、文本、图像等。<br>Graphics类提供了绘图常用的方法，利用这些方法可以实现直线、矩形、多边形、椭圆、圆弧等形状和文本、图片的绘制操作。另外，在执行这些操作之前，还可以使用相应的方法，设置绘图的颜色、字体等状态属性。<br>Java可以分别使用Graphics和Graphics2D绘制图形，Graphics类使用不同的方法实现不同图形的绘制，例如drawLine()方法可以绘制直线、drawRect()方法用于绘制矩形、drawOval()方法用于绘制椭圆形等。</p>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217201745.png"></p>
<h6 id="Graphics2D"><a href="#Graphics2D" class="headerlink" title="Graphics2D"></a>Graphics2D</h6><p>使用Graphics类可以完成简单的图形绘制任务，但是它所实现的功能非常有限，例如无法改变线条的粗细、不能对图片使用旋转、模糊等过滤效果。<br>Graphics2D继承Graphics类，实现了功能更加强大的绘图操作的集合。由于Graphics2D类是Graphics类的扩展，也是推荐使用的Java绘图类，所以本章主要介绍如何使用Graphics2D类实现Java绘图。<br>Graphics2D是继承Graphics类编写的，它包含了Graphics类的绘图方法并添加了更强的功能，是推荐使用的绘图类。Graphics2D可以分别使用不同的类来表示不同的形状，例如Line2D、Rectangle2D等。s</p>
<h4 id="2-绘制图形"><a href="#2-绘制图形" class="headerlink" title="2.绘制图形"></a>2.绘制图形</h4><ul>
<li>5个圆形图案</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import javax.swing.*;
public class DrawCircle extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final int OVAL_WIDTH = 80;// 圆形的宽
	private final int OVAL_HEIGHT = 80;// 圆形的高
	public DrawCircle() {
		super();
		initialize();// 调用初始化方法
	}
	// 初始化方法
	private void initialize() {
		this.setSize(300, 200);// 设置窗体大小
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 设置窗体关闭模式
		setContentPane(new DrawPanel());// 设置窗体面板为绘图面板对象
		this.setTitle("绘图实例1");// 设置窗体标题
	}
	public static void main(String[] args) {
		new DrawCircle().setVisible(true);
	}
	// 创建绘图面板
	class DrawPanel extends JPanel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void paint(Graphics g) {
			super.paint(g);
			g.drawOval(10, 10, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第1个圆形
			g.drawOval(80, 10, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第2个圆形
			g.drawOval(150, 10, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第3个圆形
			g.drawOval(50, 70, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第4个圆形
			g.drawOval(120, 70, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第5个圆形
		}
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>填充图形</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class DrawFrame extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public DrawFrame() {
		super();
		initialize();// 调用初始化方法
	}
	// 初始化方法
	private void initialize() {
		this.setSize(300, 200); // 设置窗体大小
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗体关闭模式
		add(new CanvasPanel()); // 设置窗体面板为绘图面板对象
		this.setTitle("绘图实例2"); // 设置窗体标题
	}
	public static void main(String[] args) {
		new DrawFrame().setVisible(true);
	}
	class CanvasPanel extends JPanel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void paint(Graphics g) {
			super.paint(g);
			Graphics2D g2 = (Graphics2D) g;
			Shape[] shapes = new Shape[4]; // 声明图形数组
			shapes[0] = new Ellipse2D.Double(5, 5, 100, 100); // 创建圆形对象
			// 创建矩形对象
			shapes[1] = new Rectangle2D.Double(110, 5, 100, 100); 
			shapes[2] = new Rectangle2D.Double(15, 15, 80, 80); // 创建矩形对象
			shapes[3] = new Ellipse2D.Double(120, 15, 80, 80); // 创建圆形对象
			for (Shape shape : shapes) { // 遍历图形数组
				Rectangle2D bounds = shape.getBounds2D();
				if (bounds.getWidth() == 80)
					g2.fill(shape); // 填充图形
				else
					g2.draw(shape); // 绘制图形
			}
		}
	}
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="3-绘图颜色与笔画属性"><a href="#3-绘图颜色与笔画属性" class="headerlink" title="3.绘图颜色与笔画属性"></a>3.绘图颜色与笔画属性</h4><h6 id="设置颜色"><a href="#设置颜色" class="headerlink" title="设置颜色"></a>设置颜色</h6><p>使用Color类可以创建任何颜色的对象，而不用担心不同平台对该颜色的支持与否，因为Java以跨平台和与硬件无关的方式支持颜色管理。创建Color对象的构造方法如下所示：<br>Color col = new Color(int r, int g, int b)<br>或者：<br>Color col = new Color(int rgb)<br>    rgb：颜色值，该值是红、绿、蓝三原色的总和<br>    r：该参数是三原色中红色的取值<br>    g：该参数是三原色中绿色的取值<br>    b：该参数是三原色中蓝色的取值</p>
<h6 id="画笔属性"><a href="#画笔属性" class="headerlink" title="画笔属性"></a>画笔属性</h6><p>在默认情况下，Graphics绘图类使用的笔画属性是粗细为1个像素的正方形，而Java2D的Graphics2D类可以调用setStroke()方法设置笔画的属性，例如改变线条的粗细、使用实线还是虚线、定义线段端点的形状、风格等，语法如下所示：<br>setStroke(Stroke stroke)<br>stroke：Stroke接口的实现类<br>setStroke()方法必须接受一个Stroke接口的实现类作参数，java.awt包中提供了BasicStroke类，它实现了Stroke接口，并且通过不同的构造方法创建笔画属性不同的对象。</p>
<h4 id="4-绘制文本"><a href="#4-绘制文本" class="headerlink" title="4.绘制文本"></a>4.绘制文本</h4><h6 id="设置字体"><a href="#设置字体" class="headerlink" title="设置字体"></a>设置字体</h6><p>Java使用Font类封装了字体的大小、样式等属性，该类在java.awt包中定义，其构造方法可以指定字体的名称、大小和样式3个属性，语法如下所示：<br>Font(String name, int style, int size)<br>name：字体的名称<br>style：字体的样式<br>size：字体的大小</p>
<h6 id="显示文本"><a href="#显示文本" class="headerlink" title="显示文本"></a>显示文本</h6><p>Graphics2D类提供了drawString()方法，使用该方法可以实现图形上下文的文本绘制，从而实现在图片上显示文字的功能，语法如下所示：<br>drawString(String str, int x, int y);<br>或者：<br>drawString(String str, float x, float y)<br>    str：要绘制的文本字符串<br>    x：绘制字符串的水平起始位置<br>    y：绘制字符串的垂直起始位置</p>
<ul>
<li>绘制矩形，里面显示时间</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class DrawString extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Shape rect; // 矩形对象
	private Font font; // 字体对象
	private Date date; // 当前日期对象
	public DrawString() {
		rect = new Rectangle2D.Double(10, 10, 200, 80);
		font = new Font("宋体", Font.BOLD, 16);
		date = new Date();
		this.setSize(230, 140); // 设置窗体大小
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗体关闭模式
		add(new CanvasPanel()); // 设置窗体面板为绘图面板对象
		this.setTitle("绘图文本"); // 设置窗体标题
	}
	public static void main(String[] args) {
		new DrawString().setVisible(true);
	}
	class CanvasPanel extends Canvas {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void paint(Graphics g) {
			super.paint(g);
			Graphics2D g2 = (Graphics2D) g;
			g2.setColor(Color.CYAN); // 设置当前绘图颜色
			g2.fill(rect); // 填充矩形
			g2.setColor(Color.BLUE); // 设置当前绘图颜色
			g2.setFont(font); // 设置字体
			g2.drawString("现在时间是", 20, 30); // 绘制文本
			g2.drawString(String.format("%tr", date), 50, 60); // 绘制时间文本
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="5-绘制图片"><a href="#5-绘制图片" class="headerlink" title="5.绘制图片"></a>5.绘制图片</h4><p>绘图类不仅可以绘制图形和文本，还可以使用drawImage()方法将图片资源显示到绘图上下文中，而且可以实现各种特效处理，例如图片的缩放、翻转等。下面主要介绍如何显示图片，语法如下所示：</p>
<pre class="line-numbers language-none"><code class="language-none">drawImage(Image img, int x, int y, ImageObserver observer)<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ul>
<li>窗体中显示图片</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import java.net.*;
import javax.swing.*;
public class DrawImage extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Image img;
	public DrawImage() {
		URL imgUrl = DrawImage.class.getResource("img.jpg");// 获取图片资源的路径
		img = Toolkit.getDefaultToolkit().getImage(imgUrl); // 获取图片资源
		this.setSize(440, 300); // 设置窗体大小
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗体关闭模式
		add(new CanvasPanel()); // 设置窗体面板为绘图面板对象
		this.setTitle("绘制图片"); // 设置窗体标题
	}
	public static void main(String[] args) {
		new DrawImage().setVisible(true);
	}
	class CanvasPanel extends Canvas {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void paint(Graphics g) {
			super.paint(g);
			Graphics2D g2 = (Graphics2D) g;
			g2.drawImage(img, 0, 0, this); // 显示图片
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="6-图像处理"><a href="#6-图像处理" class="headerlink" title="6.图像处理"></a>6.图像处理</h4><h6 id="放大与缩小"><a href="#放大与缩小" class="headerlink" title="放大与缩小"></a>放大与缩小</h6><p>想要实现图片的放大与缩小则需要使用它的重载方法，语法如下所示：</p>
<pre class="line-numbers language-none"><code class="language-none">drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>该方法将img图片显示在x、y指定的位置上，并指定图片的宽度和高度属性。方法中涉及到的参数说明如下表所示。</p>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217202512.png"></p>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import java.net.*;
import javax.swing.*;
public class ImageZoom extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Image img;
	private JPanel contentPanel = null;
	private JSlider jSlider = null;
	private int imgWidth, imgHeight;
	private Canvas canvas = null;
	public ImageZoom() {
		initialize(); // 调用初始化方法
	}
	// 界面初始化方法
	private void initialize() {
		URL imgUrl = ImageZoom.class.getResource("img.jpg");// 获取图片资源的路径
		img = Toolkit.getDefaultToolkit().getImage(imgUrl);// 获取图片资源
		canvas = new MyCanvas();
		this.setBounds(100, 100, 800, 600); // 设置窗体大小和位置
		this.setContentPane(getContentPanel()); // 设置内容面板
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗体关闭模式
		this.setTitle("绘制图片"); // 设置窗体标题
	}
	// 内容面板的布局
	private JPanel getContentPanel() {
		if (contentPanel == null) {
			contentPanel = new JPanel();
			contentPanel.setLayout(new BorderLayout());
			contentPanel.add(getJSlider(), BorderLayout.SOUTH);
			contentPanel.add(canvas, BorderLayout.CENTER);
		}
		return contentPanel;
	}
	// 获取滑块组件
	private JSlider getJSlider() {
		if (jSlider == null) {
			jSlider = new JSlider();
			jSlider.setMaximum(1000);
			jSlider.setValue(100);
			jSlider.setMinimum(1);
			jSlider.addChangeListener(new javax.swing.event.ChangeListener() {
				public void stateChanged(javax.swing.event.ChangeEvent e) {
					canvas.repaint();
				}
			});
		}
		return jSlider;
	}
	// 主方法
	public static void main(String[] args) {
		new ImageZoom().setVisible(true);
	}
	// 画板类
	class MyCanvas extends Canvas {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void paint(Graphics g) {
			int newW = 0, newH = 0;
			imgWidth = img.getWidth(this); // 获取图片宽度
			imgHeight = img.getHeight(this); // 获取图片高度
			float value = jSlider.getValue();// 滑块组件的取值
			newW = (int) (imgWidth * value / 100);// 计算图片放大后的宽度
			newH = (int) (imgHeight * value / 100);// 计算图片放大后的高度
			g.drawImage(img, 0, 0, newW, newH, this);// 绘制指定大小的图片
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="图像翻转"><a href="#图像翻转" class="headerlink" title="图像翻转"></a>图像翻转</h6><p>图像的翻转需要使用drawImage()方法的另一个重载方法，语法如下所示：<br><code>drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)</code></p>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210217202543.png"></p>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.net.URL;
import javax.swing.*;

public class PartImage extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Image img;
	private int dx1, dy1, dx2, dy2;
	private int sx1, sy1, sx2, sy2;
	private JPanel jPanel = null;
	private JPanel jPanel1 = null;
	private JButton jButton = null;
	private JButton jButton1 = null;
	private MyCanvas canvasPanel = null;
	
	public PartImage() {
		dx2 = sx2 = 300; // 初始化图像大小
		dy2 = sy2 = 200;
		initialize(); // 调用初始化方法
	}
	
	// 界面初始化方法
	private void initialize() {
		URL imgUrl = PartImage.class.getResource("cow.jpg");// 获取图片资源的路径
		img = Toolkit.getDefaultToolkit().getImage(imgUrl); // 获取图片资源
		this.setBounds(100, 100, 300, 260); // 设置窗体大小和位置
		this.setContentPane(getJPanel());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗体关闭模式
		this.setTitle("图片翻转"); // 设置窗体标题
	}
	
	// 获取内容面板的方法
	private JPanel getJPanel() {
		if (jPanel == null) {
			jPanel = new JPanel();
			jPanel.setLayout(new BorderLayout());
			jPanel.add(getControlPanel(), BorderLayout.SOUTH);
			jPanel.add(getMyCanvas1(), BorderLayout.CENTER);
		}
		return jPanel;
	}
	
	// 获取按钮控制面板的方法
	private JPanel getControlPanel() {
		if (jPanel1 == null) {
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = 1;
			gridBagConstraints.gridy = 0;
			jPanel1 = new JPanel();
			jPanel1.setLayout(new GridBagLayout());
			jPanel1.add(getJButton(), new GridBagConstraints());
			jPanel1.add(getJButton1(), gridBagConstraints);
		}
		return jPanel1;
	}
	
	// 获取水平翻转按钮
	private JButton getJButton() {
		if (jButton == null) {
			jButton = new JButton();
			jButton.setText("水平翻转");
			jButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					sx1 = Math.abs(sx1 - 300);
					sx2 = Math.abs(sx2 - 300);
					canvasPanel.repaint();
				}
			});
		}
		return jButton;
	}
	
	// 获取垂直翻转按钮
	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setText("垂直翻转");
			jButton1.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					sy1 = Math.abs(sy1 - 200);
					sy2 = Math.abs(sy2 - 200);
					canvasPanel.repaint();
				}
			});
		}
		return jButton1;
	}
	
	// 获取画板面板
	private MyCanvas getMyCanvas1() {
		if (canvasPanel == null) {
			canvasPanel = new MyCanvas();
		}
		return canvasPanel;
	}
	
	// 主方法
	public static void main(String[] args) {
		new PartImage().setVisible(true);
	}
	
	// 画板
	class MyCanvas extends JPanel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void paint(Graphics g) {
			g.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, this);// 绘制指定大小的图片
		}
	}
} // @jve:decl-index=0:visual-constraint="10,10"<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="图片旋转"><a href="#图片旋转" class="headerlink" title="图片旋转"></a>图片旋转</h6><p>图像的旋转需要调用Graphics2D类的rotate()方法，该方法将根据指定的弧度旋转图像，语法如下所示：<br><code>rotate(double theta)</code><br>theta：旋转的弧度</p>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import java.net.URL;
import javax.swing.*;
public class RotateImage extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Image img;
	private MyCanvas canvasPanel = null;
	public RotateImage() {
		initialize(); // 调用初始化方法
	}
	// 界面初始化方法
	private void initialize() {
		// 获取图片资源的路径
		URL imgUrl = RotateImage.class.getResource("cow.jpg");
		img = Toolkit.getDefaultToolkit().getImage(imgUrl); // 获取图片资源
		canvasPanel = new MyCanvas();
		this.setBounds(100, 100, 400, 350); // 设置窗体大小和位置
		add(canvasPanel);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗体关闭模式
		this.setTitle("图片旋转"); // 设置窗体标题
	}
	// 主方法
	public static void main(String[] args) {
		new RotateImage().setVisible(true);
	}
	// 画板
	class MyCanvas extends JPanel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void paint(Graphics g) {
			Graphics2D g2 = (Graphics2D) g;
			g2.rotate(Math.toRadians(5));
			g2.drawImage(img, 70, 10, 300, 200, this);// 绘制指定大小的图片
			g2.rotate(Math.toRadians(5));
			g2.drawImage(img, 70, 10, 300, 200, this);// 绘制指定大小的图片
			g2.rotate(Math.toRadians(5));
			g2.drawImage(img, 70, 10, 300, 200, this);// 绘制指定大小的图片
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="图片倾斜"><a href="#图片倾斜" class="headerlink" title="图片倾斜"></a>图片倾斜</h6><p>可以使用Graphics2D类提供的shear()方法设置绘图的倾斜方向，从而实现使图像倾斜的效果，语法如下所示：<br><code>shear(double shx, double shy)</code><br>shx：水平方向的倾斜量<br>shy：垂直方向的倾斜量</p>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import java.net.URL;
import javax.swing.*;
public class TiltImage extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Image img;
	private MyCanvas canvasPanel = null;
	public TiltImage() {
		initialize(); // 调用初始化方法
	}
	// 界面初始化方法
	private void initialize() {
		// 获取图片资源的路径
		URL imgUrl = TiltImage.class.getResource("cow.jpg");
		img = Toolkit.getDefaultToolkit().getImage(imgUrl); // 获取图片资源
		canvasPanel = new MyCanvas();
		this.setBounds(100, 100, 400, 300); // 设置窗体大小和位置
		add(canvasPanel);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗体关闭模式
		this.setTitle("图片倾斜"); // 设置窗体标题
	}
	// 主方法
	public static void main(String[] args) {
		new TiltImage().setVisible(true);
	}
	// 画板
	class MyCanvas extends JPanel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void paint(Graphics g) {
			Graphics2D g2 = (Graphics2D) g;
			g2.shear(0.3, 0);
			g2.drawImage(img, 0, 0, 300, 200, this);// 绘制指定大小的图片
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="7-播放音频文件"><a href="#7-播放音频文件" class="headerlink" title="7.播放音频文件"></a>7.播放音频文件</h4><p>简单的播放音频，可以使用Applet类的newAudioClip()方法创建音频剪辑对象，然后调用该对象的play()方法播放音频。<br>语法如下：<br><code>newAudioClip(URL url)</code><br>其中，参数url是指音频文件的URL路径。<br>该方法将返回AudioClip类的实例对象，该对象可以通过play()、stop()和loop()方法实现音频的播放、停止和循环播放。AudioClip类位于java.awt包中。</p>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.applet.*;
import java.awt.*;
import java.io.File;
import java.net.MalformedURLException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

public class MusicPlay extends JFrame {
	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JTextField filePath = null;
	private JButton openFile = null;
	private JButton playButton = null;
	private File selectedFile;
	private AudioClip audioClip;
	
	private JTextField getJTextField() {
		if (filePath == null) {
			filePath = new JTextField();
			filePath.setPreferredSize(new Dimension(200, 22));
			filePath.setEditable(false);
		}
		return filePath;
	}
	
	// 获取选择文件按钮的方法
	private JButton getOpenFile() {
		if (openFile == null) {
			openFile = new JButton();
			openFile.setText("选择文件");
			openFile.addActionListener(new java.awt.event.ActionListener() {
				
				public void actionPerformed(java.awt.event.ActionEvent e) {
					JFileChooser fileChooser = new JFileChooser();
					fileChooser
							.setFileFilter(new FileNameExtensionFilter(
									"支持的音频文件（*.mid、*.wav、*.au", "wav",
									"au", "mid"));
					fileChooser.showOpenDialog(MusicPlay.this);
					selectedFile = fileChooser.getSelectedFile();
					filePath.setText(selectedFile.getAbsolutePath());
				}
			});
		}
		return openFile;
	}
	
	// 获取播放按钮的方法
	private JButton getPlayButton() {
		if (playButton == null) {
			playButton = new JButton();
			playButton.setText("播放");
			playButton
					.addActionListener(new java.awt.event.ActionListener() {
						
						public void actionPerformed(
								java.awt.event.ActionEvent e) {
							if (selectedFile != null) {
								try {
									if (audioClip != null)
										audioClip.stop();
									audioClip = Applet
											.newAudioClip(selectedFile
													.toURI().toURL());
									audioClip.play();
								} catch (MalformedURLException e1) {
									e1.printStackTrace();
								}
							}
						}
					});
		}
		return playButton;
	}
	
	public static void main(String[] args) {
		MusicPlay thisClass = new MusicPlay();
		thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		thisClass.setVisible(true);
	}
	
	public MusicPlay() {
		super();
		initialize();
	}
	
	// 初始化方法
	private void initialize() {
		this.setSize(408, 79);
		this.setContentPane(getJContentPane());
		this.setTitle("JFrame");
	}
	
	// 初始化内容面板的方法
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new FlowLayout());
			jContentPane.add(getJTextField(), null);
			jContentPane.add(getOpenFile(), null);
			jContentPane.add(getPlayButton(), null);
		}
		return jContentPane;
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="作业"><a href="#作业" class="headerlink" title="作业"></a>作业</h6><pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.Graphics;

import javax.swing.JPanel;

public class DrawPanel extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public DrawPanel() {
		super();
		//
	}

	@Override
	protected void paintComponent(Graphics g) {
		// 矩形
		super.paintComponent(g);
		g.drawRect(10, 10, 100, 50);
		// 三角
		int[] xs = {10, 50, 30};
		int[] ys = {80, 80, 110};
		g.drawPolygon(xs, ys, 3);
		// 圆形
		g.drawOval(130,10,80,80);
		// 椭圆
		g.drawOval(60,80,80,50);
	}

}


package com.lzw;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class FrameDraw extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel panel;
	public static void main(String args[]) {
		try {
			FrameDraw frame = new FrameDraw();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public FrameDraw() {
		super();
		setBounds(100, 100, 269, 185);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().add(getPanel(), BorderLayout.CENTER);
		//
	}
	protected JPanel getPanel() {
		if (panel == null) {
			panel = new DrawPanel();
		}
		return panel;
	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class DrawWindow extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel panel;
	public static void main(String args[]) {
		try {
			DrawWindow frame = new DrawWindow();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public DrawWindow() {
		super();
		setBounds(100, 100, 458, 357);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().add(getPanel(), BorderLayout.CENTER);
		//
	}
	protected JPanel getPanel() {
		if (panel == null) {
			panel = new MyPanel();
		}
		return panel;
	}

}



package com.lzw;

import java.awt.*;
import java.util.Date;

import javax.swing.JPanel;

public class MyPanel extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final int OVAL_WIDTH = 150;
	private static final int OVAL_HEIGHT = 150;

	public MyPanel() {
		super();
		//
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D) g;
		g2.setStroke(new BasicStroke(4.0F));
		g2.setColor(Color.BLUE);
		g2.drawOval(10, 10, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第1个圆形
		g2.setStroke(new BasicStroke(8.0F));
		g2.setColor(Color.CYAN);
		g2.drawOval(130, 10, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第2个圆形
		g2.setStroke(new BasicStroke(2.0F));
		g2.setColor(Color.GREEN);
		g2.drawOval(250, 10, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第3个圆形
		g2.setStroke(new BasicStroke(5.0F));
		g2.setColor(Color.MAGENTA);
		g2.drawOval(70, 120, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第4个圆形
		g2.setStroke(new BasicStroke(9.0F));
		g2.setColor(Color.ORANGE);
		g2.drawOval(190, 120, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第5个圆形
		Date now=new Date();
		String nowStr = String.format("%tY年%tm月%td日", new Date[]{now, now, now});
		Font font = new Font("宋体",Font.BOLD,14);
		g2.setFont(font);
		g2.drawString(nowStr, 80, 300);
	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import javax.swing.*;
public class CanvasPanel extends JPanel implements Runnable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Image back;
	private Image cloud;
	int time;
	private Thread thread;
	private boolean play = true;
	int width = 458;
	int height = 357;
	int x = width;
	public CanvasPanel() {
		super();
		back = new ImageIcon(getClass().getResource("back.jpg")).getImage();
		cloud = new ImageIcon(getClass().getResource("cloud.png")).getImage();
		time = 100;
		play = true;
		if (thread == null || !thread.isAlive())
			thread = new Thread(this);
		thread.start();
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(back, 0, 0, width, height, this);
		g.drawImage(cloud, x, 10, this);

		x -= 2;
		if (x &lt;= -cloud.getWidth(this))
			x = width;

	}
	public void run() {
		while (play) {
			try {
				Thread.sleep(time);
			} catch (Exception e) {
				e.printStackTrace();
			}
			repaint();
		}
	}
}



package com.lzw;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class ImageRun extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel panel;
	public static void main(String args[]) {
		try {
			ImageRun frame = new ImageRun();
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public ImageRun() {
		super();
		setBounds(100, 100, 458, 357);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().add(getPanel(), BorderLayout.CENTER);
		//
	}
	protected JPanel getPanel() {
		if (panel == null) {
			panel = new CanvasPanel();
		}
		return panel;
	}

}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="二、打印技术"><a href="#二、打印技术" class="headerlink" title="二、打印技术"></a>二、打印技术</h2><h6 id="打印控制类"><a href="#打印控制类" class="headerlink" title="打印控制类"></a>打印控制类</h6><p>PrinterJob类是控制打印的主要类，Java应用程序可以调用此类中的方法实现设置打印任务、打开“打印”对话框、执行页面打印等任务。本节将介绍控制打印任务的常用方法。<br>1．获取PrinterJob对象<br>2．打印任务的名称属性<br>3．设置打印页面<br>4．获取打印用户<br>5．打印状态</p>
<h6 id="“打印”对话框"><a href="#“打印”对话框" class="headerlink" title="“打印”对话框"></a>“打印”对话框</h6><p>用户可以使用“打印”对话框对打印任务进行设置，如打印纸张大小、是否彩色打印、打印纸方向和打印份数等属性。“打印”对话框如图27.2所示。调用PrinterJob类的printDialog()方法将打开“打印”对话框，该方法的返回值是boolean类型。<br>语法如下：<br>boolean ok = job.printDialog()<br>其中，job是PrinterJob类的实例对象。<br>当用户单击“打印”对话框中的“确定”按钮时，该方法返回true；当单击“打印”对话框中的“取消”按钮时，该方法返回false。</p>
<h6 id="打印页面"><a href="#打印页面" class="headerlink" title="打印页面"></a>打印页面</h6><p>打印页面是指打印任务要执行打印的内容，这些内容可以是文本、图片、网页和图形等，在第26章中所讲的所有绘图内容都可以作为打印内容。打印内容必须实现Printable接口，该接口位于java.awt.print包中，接口中只包含一个方法。<br>语法如下：<br>print(Graphics graphics, PageFormat pageFormat, int pageIndex)<br>graphics：绘制打印页面的图形上下文。<br>pageFormat：将绘制打印页面的格式属性，如方向和大小。<br>pageIndex：当前打印页的索引。</p>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.awt.print.*;

public class StudyPrint {
	public static void main(String[] args) {
		try {
			PrinterJob job = PrinterJob.getPrinterJob();
			if (!job.printDialog())
				return;
			job.setPrintable(new Printable() {
				private final int OVAL_WIDTH = 130; // 圆形的宽
				private final int OVAL_HEIGHT = 130; // 圆形的高
				
				public int print(Graphics graphics, PageFormat pageFormat,
						int pageIndex) throws PrinterException {
					if (pageIndex &gt; 0)
						return Printable.NO_SUCH_PAGE;
					int x = (int) pageFormat.getImageableX();
					int y = (int) pageFormat.getImageableY();
					Graphics2D g2 = (Graphics2D) graphics;
					g2.setStroke(new BasicStroke(4.0F));
					g2.setColor(Color.BLUE);
					// 绘制第1个圆形
					g2.drawOval(x + 10, y + 10, OVAL_WIDTH, OVAL_HEIGHT); 
					g2.setColor(Color.CYAN);
					// 绘制第2个圆形
					g2.drawOval(x + 130, y + 10, OVAL_WIDTH, OVAL_HEIGHT); 
					g2.setColor(Color.GREEN);
					// 绘制第3个圆形
					g2.drawOval(x + 250, y + 10, OVAL_WIDTH, OVAL_HEIGHT); 
					g2.setColor(Color.MAGENTA);
					// 绘制第4个圆形
					g2.drawOval(x + 70, y + 120, OVAL_WIDTH, OVAL_HEIGHT); 
					g2.setColor(Color.ORANGE);
					// 绘制第5个圆形
					g2.drawOval(x + 190, y + 120, OVAL_WIDTH, OVAL_HEIGHT); 
					return Printable.PAGE_EXISTS;
				}
			});
			job.setJobName("打印图形");
			job.print();
		} catch (PrinterException e) {
			e.printStackTrace();
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h6 id="多页打印"><a href="#多页打印" class="headerlink" title="多页打印"></a>多页打印</h6><p>虽然实现Printable接口并重写print()方法，可以实现自己的打印页对象，但是在实际的程序开发中经常需要进行多页打印，这就需要使用java.awt.print包所提供的Book类对多个打印页进行封装。使用Book类的append()方法可以将多个打印页面添加到Book类的实例对象中，这可以看作是为一本书添加多个章节和页码。该方法有两种重载形式。语法如下：<br>append(Printable painter, PageFormat page)<br>或<br>append(Printable painter, PageFormat page, int numPages)<br>    painter：实现Printable接口的类，也就是打印页。<br>    page：将绘制打印页面的格式属性，如方向和大小。<br>    numPages：要添加到Book中的页数。</p>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;

import java.awt.*;
import java.awt.print.*;

public class MultiPagePrint {
	static class PrintPage implements Printable {
		public int print(Graphics graphics, PageFormat pageFormat,
				int pageIndex) throws PrinterException {
			// 获取可打印区域坐标的X位置
			int x = (int) pageFormat.getImageableX();
			// 获取可打印区域坐标的Y位置
			int y = (int) pageFormat.getImageableY();
			Graphics2D g2 = (Graphics2D) graphics;
			// 绘制文本
			g2.drawString("多页打印实例的第" + pageIndex + "页", x, y + 10);
			return Printable.PAGE_EXISTS; // 返回PAGE_EXISTS
		}
	}
	
	public static void main(String[] args) {
		try {
			PrinterJob job = PrinterJob.getPrinterJob();
			if (!job.printDialog()) // 如果取消打印对话框
				return; // 终止方法执行
			Book printBook = new Book();
			PageFormat pf = new PageFormat();
			printBook.append(new PrintPage(), pf); // 添加1页
			printBook.append(new PrintPage(), pf, 5); // 添加5页
			job.setPageable(printBook); // 设置打印页
			job.setJobName("多页打印"); // 设置打印任务名称
			job.print(); // 执行打印
		} catch (PrinterException e) {
			e.printStackTrace();
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h6 id="打印预览"><a href="#打印预览" class="headerlink" title="打印预览"></a>打印预览</h6><p>打印预览机制使用户可以在打印之前，在屏幕上查看要打印的内容及打印样式，从而避免错误打印而造成纸张浪费。各类办公软件、图像处理软件等都提供打印预览功能，而Java Swing技术并没有提供打印预览对话框组件，本节将介绍如何实现自己的打印预览机制。<br>在Printable接口的print()方法中，操作的graphics是打印机的图形上下文对象。打印预览的实现原理就是将该图形上下文替换为程序界面的图形上下文，在组件的paint()方法中调用Printable接口的print()方法即可实现打印预览。</p>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;
public class PrintPreview extends JFrame implements Printable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Image img;
	private JButton previewButton = null;
	private JPanel controlPanel = null;
	private JButton printButton = null;
	private Canvas canvas = null;
	private PageFormat pf;
	public PrintPreview() {
		canvas = new MyCanvas();
		pf = new PageFormat();
		pf.setOrientation(PageFormat.LANDSCAPE);
		printButton = new JButton("开始打印");
		img = Toolkit.getDefaultToolkit().getImage(
				PrintPreview.class.getResource("eat.png"));
		initialize();
	}
	// 界面初始化方法
	private void initialize() {
		this.setSize(new Dimension(840, 700));
		BorderLayout borderLayout = new BorderLayout();
		borderLayout.setHgap(10);
		setLayout(borderLayout);
		add(getControlPanel(), BorderLayout.SOUTH);
		add(canvas, BorderLayout.CENTER);
		this.setTitle("打印预览");
	}
	// 实现paint()方法
	public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
			throws PrinterException {
		int x = (int) pageFormat.getImageableX(); // 获取可打印区域坐标的X位置
		int y = (int) pageFormat.getImageableY(); // 获取可打印区域坐标的Y位置
		Graphics2D g2 = (Graphics2D) graphics;
		g2.drawImage(img, x, y, this); // 绘制图像
		return Printable.PAGE_EXISTS; // 返回PAGE_EXISTS
	}
	// 打印预览按钮
	private JButton getPreviewButton() {
		if (previewButton == null) {
			previewButton = new JButton();
			previewButton.setText("打印预览");
			previewButton
					.addActionListener(new java.awt.event.ActionListener() {
						public void actionPerformed(
								java.awt.event.ActionEvent e) {
							PrinterJob job = PrinterJob.getPrinterJob();
							pf = job.pageDialog(pf);
							canvas.repaint();
						}
					});
		}
		return previewButton;
	}
	// 控制面板
	private JPanel getControlPanel() {
		if (controlPanel == null) {
			FlowLayout flowLayout = new FlowLayout();
			flowLayout.setVgap(2);
			flowLayout.setHgap(30);
			controlPanel = new JPanel();
			controlPanel.setLayout(flowLayout);
			controlPanel.add(getPreviewButton(), null);
			controlPanel.add(printButton, null);
		}
		return controlPanel;
	}
	
	class MyCanvas extends Canvas {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void paint(Graphics g) {
			try {
				super.paint(g);
				Graphics2D g2 = (Graphics2D) g;
				g2.translate(10, 10);
				int x = (int) (pf.getImageableX() - 1);
				int y = (int) (pf.getImageableY() - 1);
				int width = (int) (pf.getImageableWidth() + 1);
				int height = (int) (pf.getImageableHeight() + 1);
				int mw = (int) pf.getWidth();
				int mh = (int) pf.getHeight();
				g2.drawRect(0, 0, mw, mh);
				g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_ROUND,
						BasicStroke.JOIN_ROUND, 10f, new float[] { 5, 5 },
						0f));
				g2.drawRect(x, y, width, height);
				PrintPreview.this.print(g, pf, 0);
			} catch (PrinterException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		try {
			PrintPreview pp = new PrintPreview();
			pp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			pp.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="作业-1"><a href="#作业-1" class="headerlink" title="作业"></a>作业</h6><pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import java.awt.print.*;
public class PrintText {
	public static void main(String[] args) {
		try {
			PrinterJob job = PrinterJob.getPrinterJob();
			if (!job.printDialog())
				return;
			job.setPrintable(new Printable() {
				public int print(Graphics graphics, PageFormat pageFormat,
						int pageIndex) throws PrinterException {
					if (pageIndex &gt; 0)
						return Printable.NO_SUCH_PAGE;
					int x = (int) pageFormat.getImageableX();
					int y = (int) pageFormat.getImageableY();
					Graphics2D g2=(Graphics2D) graphics;
					g2.setFont(new Font("宋体",Font.PLAIN,34));
					g2.setColor(Color.BLUE);
					g2.drawString("通过本书学习",x, y+30);
					g2.setFont(new Font("宋体",Font.BOLD,48));
					g2.setColor(Color.RED);
					g2.drawString("JAVA",x, y+90);
					g2.setFont(new Font("宋体",Font.ITALIC,34));
					g2.setColor(Color.BLUE);
					g2.drawString("可以快速入门，并迅速提高",x, y+150);
					return Printable.PAGE_EXISTS;
				}
			});
			job.setJobName("打印图形");
			job.print();
		} catch (PrinterException e) {
			e.printStackTrace();
		}
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">package com.lzw;
import java.awt.*;
import java.awt.print.*;

import javax.swing.*;

/**
 * 
 */

public class StudyPreviewCanvas extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private PageFormat pf;
	private Image img;

	public StudyPreviewCanvas(PageFormat pf, Image img) {
		this.pf=pf;
		this.img=img;
		setPreferredSize(new Dimension((int) pf.getWidth() + 40, (int) pf
				.getHeight() + 80));
	}

	@Override
	protected void paintComponent(Graphics g) {
		// TODO 自动生成方法存根
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D) g;
		g2.translate(20, 40);
		int x = (int) (pf.getImageableX() - 1);
		int y = (int) (pf.getImageableY() - 1);
		int width = (int) (pf.getImageableWidth() + 1);
		int height = (int) (pf.getImageableHeight() + 1);
		int mw = (int) pf.getWidth();
		int mh = (int) pf.getHeight();
		g2.drawImage(img, x + 1, y + 1, this); // 绘制图像
		g2.drawRect(0, 0, mw, mh);
		g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_ROUND,
				BasicStroke.JOIN_ROUND, 10f, new float[]{5, 5}, 0f));
		g2.drawRect(x, y, width, height);
	}
}

package com.lzw;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class StudyPrintPreview {
	private final static int OVAL_WIDTH = 130; // 圆形的宽
	private final static int OVAL_HEIGHT = 130; // 圆形的高
	private static int x;
	private static int y;

	public static void main(String[] args) {
		PageFormat pf = new PageFormat();
		PrinterJob job = PrinterJob.getPrinterJob();
		BufferedImage img = new BufferedImage(400, 300,
				BufferedImage.TYPE_INT_RGB);
		if (!job.printDialog())
			return;
		job.setPrintable(new Printable() {
			public int print(Graphics graphics, PageFormat pageFormat,
					int pageIndex) throws PrinterException {
				if (pageIndex &gt; 0)
					return Printable.NO_SUCH_PAGE;
				x = (int) pageFormat.getImageableX();
				y = (int) pageFormat.getImageableY();
				drawPage(graphics, x, y);
				return Printable.PAGE_EXISTS;
			}
		});
		job.setJobName("打印图形");
		pf = job.pageDialog(pf);
		drawPage(img.getGraphics(), x, y);
		StudyPreviewCanvas canvas = new StudyPreviewCanvas(pf, img);
		JScrollPane spanel = new JScrollPane(canvas);
		JFrame previewDialog = new JFrame();
		previewDialog.getContentPane().add(spanel);
		previewDialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		previewDialog.setSize(800, 600);
		previewDialog.setVisible(true);
		canvas.repaint();
	}
	private static void drawPage(Graphics graphics, int x, int y) {
		Graphics2D g2 = (Graphics2D) graphics;
		g2.setColor(Color.WHITE);
		g2.fillRect(0, 0, 400, 300);
		g2.setStroke(new BasicStroke(4.0F));
		g2.setColor(Color.BLUE);
		g2.drawOval(x + 10, y + 10, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第1个圆形
		g2.setColor(Color.CYAN);
		g2.drawOval(x + 130, y + 10, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第2个圆形
		g2.setColor(Color.GREEN);
		g2.drawOval(x + 250, y + 10, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第3个圆形
		g2.setColor(Color.MAGENTA);
		g2.drawOval(x + 70, y + 120, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第4个圆形
		g2.setColor(Color.ORANGE);
		g2.drawOval(x + 190, y + 120, OVAL_WIDTH, OVAL_HEIGHT); // 绘制第5个圆形
	}
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">import java.awt.*;
import java.awt.print.PageFormat;

import javax.swing.*;

/**
 * 
 */

public class MyCanvas extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	private PageFormat pf;
	private Image img;

	public MyCanvas(PageFormat pf, Image img) {
		this.pf=pf;
		this.img=img;
		setPreferredSize(new Dimension((int) pf.getWidth() + 40, (int) pf
				.getHeight() + 80));
	}

	@Override
	protected void paintComponent(Graphics g) {
		// TODO 自动生成方法存根
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D) g;
		g2.translate(20, 40);
		int x = (int) (pf.getImageableX() - 1);
		int y = (int) (pf.getImageableY() - 1);
		int width = (int) (pf.getImageableWidth() + 1);
		int height = (int) (pf.getImageableHeight() + 1);
		int mw = (int) pf.getWidth();
		int mh = (int) pf.getHeight();
		g2.drawImage(img, x + 1, y + 1, this); // 绘制图像
		g2.drawRect(0, 0, mw, mh);
		g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_ROUND,
				BasicStroke.JOIN_ROUND, 10f, new float[]{5, 5}, 0f));
		g2.drawRect(x, y, width, height);
	}
}





import java.awt.*;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.awt.print.*;

import javax.swing.*;
import javax.swing.JLabel;
import javax.swing.border.*;
public class PrintPanel extends JPanel implements Printable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JLabel label;
	private JButton printButton;
	private JButton previewButton;
	private JPanel controlPanel;
	private Image img;
	private Dimension size;
	private PrinterJob job;
	private JFrame previewDialog;
	PageFormat pf;
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(600, 480);
		PrintPanel canvas = new PrintPanel();
		frame.add(canvas);
		frame.setVisible(true);
	}
	public PrintPanel() {
		super();
		setLayout(new BorderLayout());
		setBackground(Color.WHITE);
		addMouseMotionListener(new MouseMotionAdapter() {
			public void mouseDragged(MouseEvent e) {
				Point point = e.getPoint();
				Graphics2D g2 = (Graphics2D) img.getGraphics();
				g2.setStroke(new BasicStroke(5));
				g2.drawLine(point.x, point.y, point.x, point.y);
				img.flush();
				repaint();
			}
		});
		add(getControlPanel(), BorderLayout.SOUTH);
		pf = new PageFormat();
		pf.setOrientation(PageFormat.LANDSCAPE);
		job = PrinterJob.getPrinterJob();
		previewDialog = new JFrame();
		previewDialog.setSize(800, 600);
	}
	private void drawPage(Graphics2D g2) {
		g2.drawImage(img, 0, 0, this);
	}
	protected JButton getPreviewButton() {
		if (previewButton == null) {
			previewButton = new JButton();
			previewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					pf = job.pageDialog(pf);
					MyCanvas canvas = new MyCanvas(pf,img);
					JScrollPane spanel = new JScrollPane(canvas);
					previewDialog.getContentPane().add(spanel);
					previewDialog.setVisible(true);
					canvas.repaint();
				}
			});
			previewButton.setText("打印预览");
		}
		return previewButton;
	}
	protected JButton getPrintButton() {
		if (printButton == null) {
			printButton = new JButton();
			printButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try {
						job.setPrintable(PrintPanel.this);
						job.setJobName("打印图形");
						job.print();
					} catch (PrinterException e1) {
						e1.printStackTrace();
					}
				}
			});
			printButton.setText("打印");
		}
		return printButton;
	}

	protected JPanel getControlPanel() {
		if (controlPanel == null) {
			controlPanel = new JPanel();
			controlPanel.setBorder(new LineBorder(Color.BLUE, 1, false));
			final FlowLayout flowLayout = new FlowLayout();
			flowLayout.setAlignment(FlowLayout.LEFT);
			flowLayout.setHgap(20);
			controlPanel.setLayout(flowLayout);
			controlPanel.add(getLabel());
			controlPanel.add(getPreviewButton());
			controlPanel.add(getPrintButton());
		}
		return controlPanel;
	}
	@Override
	protected void paintComponent(Graphics g) {
		if (size == null) {
			size = getSize();
			img = createImage(size.width, size.height);
		}
		Graphics2D g2 = (Graphics2D) g;
		drawPage(g2);
	}
	public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
			throws PrinterException {
		if (pageIndex &gt; 0)
			return Printable.NO_SUCH_PAGE;
		int x = (int) pageFormat.getImageableX();
		int y = (int) pageFormat.getImageableY();
		Graphics2D g2 = (Graphics2D) graphics;
		g2.translate(x, y);
		drawPage(g2);
		return Printable.PAGE_EXISTS;
	}
	/**
	 * @return
	 */
	protected JLabel getLabel() {
		if (label == null) {
			label = new JLabel();
			label.setForeground(Color.RED);
			label.setText("请用鼠标在界面上画线或图形，进行预览");
		}
		return label;
	}
}
s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">lxx</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://xinxinliang.github.io/2021/02/19/java-kuo-zhan-lei-5-awt-hui-tu-he-yin-pin-bo-fang-da-yin-ji-zhu/">http://xinxinliang.github.io/2021/02/19/java-kuo-zhan-lei-5-awt-hui-tu-he-yin-pin-bo-fang-da-yin-ji-zhu/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">lxx</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                                    <span class="chip bg-color">编程语言</span>
                                </a>
                            
                                <a href="/tags/Java%E6%89%A9%E5%B1%95%E7%B1%BB/">
                                    <span class="chip bg-color">Java扩展类</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="https://gitee.com/liangxinixn/guitar/raw/master/image01/20200726220206.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="https://gitee.com/liangxinixn/guitar/raw/master/image01/20200726220308.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/02/24/cong-ling-kai-shi-xue-python-wang-luo-pa-chong/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-g8p9j3.jpg" class="responsive-img" alt="《从零开始学Python网络爬虫》">
                        
                        <span class="card-title">《从零开始学Python网络爬虫》</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-02-24
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/python%E7%88%AC%E8%99%AB/" class="post-category">
                                    python爬虫
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%94%B5%E5%AD%90%E4%B9%A6/">
                        <span class="chip bg-color">电子书</span>
                    </a>
                    
                    <a href="/tags/%E6%BA%90%E7%A0%81%E7%89%88/">
                        <span class="chip bg-color">源码版</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/02/19/java-kuo-zhan-lei-4-shu-ju-ku-cao-zuo/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-eyp68r.jpg" class="responsive-img" alt="Java扩展类4：数据库操作">
                        
                        <span class="card-title">Java扩展类4：数据库操作</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-02-19
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                        <span class="chip bg-color">编程语言</span>
                    </a>
                    
                    <a href="/tags/Java%E6%89%A9%E5%B1%95%E7%B1%BB/">
                        <span class="chip bg-color">Java扩展类</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 头号咸鱼<br />'
            + '文章作者: lxx<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021</span>
            
            <span id="year">2021</span>
            <a href="/about" target="_blank">lxx</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">272.8k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/xinxinliang" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1974733812@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1974733812" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1974733812" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    
    <script>
        (function (i, s, o, g, r, a, m) {
            i["DaoVoiceObject"] = r;
            i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o), m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            a.charset = "utf-8";
            m.parentNode.insertBefore(a, m)
        })(window, document, "script", ('https:' == document.location.protocol ? 'https:' : 'http:') +
            "//widget.daovoice.io/widget/6984b559.js", "daovoice")
        daovoice('init', {
            app_id: "7b318e23"
        });
        daovoice('update');
    </script>
    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
